package com.hgd.security.evp.biz.rabbitmq;

import com.hgd.security.evp.biz.entity.EvpUser;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author By 尚
 * @date 2019/5/21 9:59
 */
@Component
public class HGDRabbitMQSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private Environment environment;

    private RabbitTemplate.ConfirmCallback confirmCallback = (correlationData, ack, cause) ->
    {
        if(ack){
            System.out.println(Thread.currentThread().getName()+
                "com.hgd.security.evp.biz.rabbitmq.HGDRabbitMQSender::org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback.confirm");
        }else{
            System.out.println(Thread.currentThread().getName()+
                "================================wrong==================================");
        }
    };

    private RabbitTemplate.ReturnCallback returnCallback =
        (message, replyCode, replyText, exchange, routingKey) -> System.err.println(
            "com.hgd.security.evp.biz.rabbitmq.HGDRabbitMQSender::org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback.returnedMessage");

    public void sendUser(EvpUser user, Map<String,Object> headersMap) {
        rabbitTemplate.setConfirmCallback(confirmCallback);
        rabbitTemplate.setReturnCallback(returnCallback);

        MessageHeaders headers=new MessageHeaders(headersMap);
        Message message= MessageBuilder.createMessage(user, headers);

        CorrelationData correlationData = new CorrelationData(user.getPhone());

        String exchange = environment.getProperty("hgd.rabbitmq.user.exchange");
        rabbitTemplate.convertAndSend(exchange,
            "userRouting.save", message, correlationData);
    }
}
